package com.example.shutdown_v1.service;

import com.example.shutdown_v1.entity.AlarmRecord;
import com.example.shutdown_v1.entity.Shop;
import com.example.shutdown_v1.repository.AlarmRecordRepository;
import com.example.shutdown_v1.repository.ShopRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 告警服务
 * 负责生成和管理告警记录
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AlarmService {

    private final AlarmRecordRepository alarmRecordRepository;
    private final ShopRepository shopRepository;
    private final SmsNotificationService smsNotificationService;

    /**
     * 创建开关未关闭告警
     * @param shopId 店铺ID
     * @param openSwitches 未关闭的开关列表（传感器ID）
     */
    @Transactional
    public void createUnclosedSwitchAlarm(Long shopId, List<String> openSwitches) {
        if (openSwitches == null || openSwitches.isEmpty()) {
            return;
        }
        
        Shop shop = shopRepository.findById(shopId).orElse(null);
        if (shop == null) {
            log.warn("店铺不存在: {}", shopId);
            return;
        }
        
        AlarmRecord alarm = new AlarmRecord();
        alarm.setShopId(shopId);
        alarm.setAlarmType("switch_not_closed");
        alarm.setAlarmLevel(2); // 1-低, 2-中, 3-高
        alarm.setAlarmContent(String.format("[%s] 检测到 %d 个开关未关闭，请及时处理！", 
                shop.getName(), openSwitches.size()));
        alarm.setRelatedSensors(String.join(",", openSwitches));
        alarm.setAlarmTime(LocalDateTime.now());
        alarm.setNotificationStatus(0); // 0-未发送, 1-已发送
        alarm.setNotificationChannels("system"); // 系统内告警
        
        alarmRecordRepository.save(alarm);
        
        log.warn("[告警] 店铺={}, 未关闭开关数={}, 传感器={}", 
                shop.getName(), openSwitches.size(), openSwitches);
        
        // 发送短信通知责任人
        sendSmsToResponsiblePerson(shop, openSwitches, alarm);
    }
    
    /**
     * 发送短信给责任人
     */
    private void sendSmsToResponsiblePerson(Shop shop, List<String> openSwitches, AlarmRecord alarm) {
        try {
            String phoneNumber = shop.getContactPhone();
            
            if (phoneNumber == null || phoneNumber.isEmpty()) {
                log.warn("[短信通知] 店铺 {} 未配置联系电话，无法发送短信", shop.getName());
                return;
            }
            
            if (!smsNotificationService.isValidPhone(phoneNumber)) {
                log.warn("[短信通知] 店铺 {} 的联系电话格式无效: {}", shop.getName(), phoneNumber);
                return;
            }
            
            // 发送短信
            boolean success = smsNotificationService.sendUnclosedSwitchAlarm(
                    shop.getName(), 
                    shop.getResponsiblePerson(), 
                    phoneNumber, 
                    openSwitches
            );
            
            // 更新告警记录的通知状态
            if (success) {
                alarm.setNotificationStatus(1); // 已发送
                alarm.setNotificationChannels("system,sms");
                alarmRecordRepository.save(alarm);
            }
            
        } catch (Exception e) {
            log.error("[短信通知] 发送失败: 店铺={}", shop.getName(), e);
        }
    }
    
    /**
     * 创建传感器离线告警
     */
    @Transactional
    public void createSensorOfflineAlarm(Long shopId, String sensorId) {
        if (shopId == null) {
            log.warn("[告警] 无法创建离线告警：shopId为null, sensorId={}", sensorId);
            return;
        }
        
        Shop shop = shopRepository.findById(shopId).orElse(null);
        if (shop == null) {
            log.warn("[告警] 无法创建离线告警：店铺不存在, shopId={}, sensorId={}", shopId, sensorId);
            return;
        }
        
        AlarmRecord alarm = new AlarmRecord();
        alarm.setShopId(shopId);
        alarm.setAlarmType("sensor_offline");
        alarm.setAlarmLevel(1);
        alarm.setAlarmContent(String.format("[%s] 传感器 %s 已离线，请检查设备！", 
                shop.getName(), sensorId));
        alarm.setRelatedSensors(sensorId);
        alarm.setAlarmTime(LocalDateTime.now());
        alarm.setNotificationStatus(0);
        
        alarmRecordRepository.save(alarm);
        log.warn("[告警] 传感器离线: shopId={}, sensorId={}", shopId, sensorId);
    }
    
    /**
     * 确认告警
     */
    @Transactional
    public boolean confirmAlarm(Long alarmId, String confirmedBy) {
        return alarmRecordRepository.findById(alarmId)
                .map(alarm -> {
                    alarm.setConfirmed(true);
                    alarm.setConfirmedBy(confirmedBy);
                    alarm.setConfirmedAt(LocalDateTime.now());
                    alarmRecordRepository.save(alarm);
                    log.info("[告警确认] ID={}, 确认人={}", alarmId, confirmedBy);
                    return true;
                })
                .orElse(false);
    }


}

